﻿using Microsoft.Data.SqlClient;
using System;
using System.Data;
using System.Threading.Tasks;

namespace EmailHelper.tool
{
    public class SqlHelper
    {


        public static String resource = "Data Source=.;Initial Catalog=CodeC;Integrated Security=True"; 
        private static SqlConnection connection;

        public static SqlConnection Connection
        {
            get 
            {
                if (connection == null)
                {
                    connection = new SqlConnection(resource);
                }
                else if (connection.State == ConnectionState.Closed)
                {
                    connection.Open();
                }
                else if (connection.State == ConnectionState.Broken)
                {
                    connection.Close();
                    connection.Open();
                }
              
                return connection;
            }
          
        }


        public static DataTable Select(String tableName,String columnName)
        {
            try
            {
                String Sql = $"SELECT * FROM {tableName}";
                SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(Sql, Connection);
                DataSet dataSet = new DataSet();
                sqlDataAdapter.Fill(dataSet);
                return dataSet.Tables[0];
            }
            catch (Exception ex)
            {
                
                return new DataTable();
            }
        }

        public async static Task<bool> Query(String sql)
        {
            SqlCommand sqlCommand = new SqlCommand(sql, Connection);

            return await sqlCommand.ExecuteNonQueryAsync() > 0 ? true : false;
        }
    }
}
